package movie.ticketing.system.view;

import movie.ticketing.system.controller.HomeController;
import movie.ticketing.system.dao.AdministratorDAO;
import movie.ticketing.system.dao.UserDAO;
import movie.ticketing.system.model.Administrator;
import movie.ticketing.system.model.User;
import movie.ticketing.system.util.SystemDB;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Home extends JFrame {
    private final HomeController homeController;
    private final UserDAO userDAO;
    private final AdministratorDAO administratorDAO;
    private final SystemDB systemDB;
    
    public Home() {
        this.homeController = new HomeController();
        this.userDAO = new UserDAO();
        this.administratorDAO = new AdministratorDAO();
        this.systemDB = new SystemDB();
        
        // 初始化数据库
        try {
            systemDB.initializeDatabase();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库初始化失败，请检查数据库配置。", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }

        // 设置窗口属性
        setTitle("电影票购票系统");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 用户登录和注册按钮
        JButton userLoginButton = new JButton("用户登录");
        JButton userRegisterButton = new JButton("用户注册");
        JButton adminLoginButton = new JButton("管理员登录");

        // 添加按钮到面板
        mainPanel.add(userLoginButton);
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(userRegisterButton);
        mainPanel.add(Box.createVerticalStrut(10));
        mainPanel.add(adminLoginButton);

        // 添加面板到窗口
        add(mainPanel, BorderLayout.CENTER);

        // 用户登录按钮事件处理
        userLoginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showUserLoginDialog();
            }
        });

        // 用户注册按钮事件处理
        userRegisterButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showUserRegisterDialog();
            }
        });

        // 管理员登录按钮事件处理
        adminLoginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAdminLoginDialog();
            }
        });
    }

    // 显示用户登录对话框
    private void showUserLoginDialog() {
        JTextField phoneField = new JTextField();
        JPasswordField passwordField = new JPasswordField();

        Object[] message = {
            "手机号:", phoneField,
            "密码:", passwordField
        };

        int option = JOptionPane.showConfirmDialog(this, message, "用户登录", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            String phone = phoneField.getText();
            String password = new String(passwordField.getPassword());

            try {
                User user = userDAO.login(phone, password);
                if (user != null) {
                    // 更新上次登录时间
                    userDAO.updateLastLoginTime(user.getId());
                    JOptionPane.showMessageDialog(this, "登录成功！欢迎，" + user.getUsername(), "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 跳转到用户主界面
                    showUserMainInterface(user);
                } else {
                    JOptionPane.showMessageDialog(this, "手机号或密码错误，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "登录失败，请检查数据库连接。", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 显示用户注册对话框
    private void showUserRegisterDialog() {
        JTextField phoneField = new JTextField();
        JTextField usernameField = new JTextField();
        JPasswordField passwordField = new JPasswordField();

        Object[] message = {
            "手机号:", phoneField,
            "用户名:", usernameField,
            "密码:", passwordField
        };

        int option = JOptionPane.showConfirmDialog(this, message, "用户注册", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            String phone = phoneField.getText();
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            if (phone.isEmpty() || username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "手机号、用户名和密码不能为空，请重新输入。", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            try {
                if (userDAO.isPhoneExists(phone)) {
                    JOptionPane.showMessageDialog(this, "该手机号已被注册，请使用其他手机号。", "错误", JOptionPane.ERROR_MESSAGE);
                } else {
                    Date registerDate = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String registerTime = sdf.format(registerDate);
                    
                    User newUser = new User(phone, username, password, registerTime, "", "");
                    userDAO.register(newUser);
                    JOptionPane.showMessageDialog(this, "注册成功，请登录。", "成功", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "注册失败，请检查数据库连接。", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 显示管理员登录对话框
    private void showAdminLoginDialog() {
        JTextField usernameField = new JTextField();
        JPasswordField passwordField = new JPasswordField();

        Object[] message = {
            "用户名:", usernameField,
            "密码:", passwordField
        };

        int option = JOptionPane.showConfirmDialog(this, message, "管理员登录", JOptionPane.OK_CANCEL_OPTION);
        if (option == JOptionPane.OK_OPTION) {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            try {
                Administrator admin = administratorDAO.login(username, password);
                if (admin != null) {
                    JOptionPane.showMessageDialog(this, "登录成功！欢迎，管理员", "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 跳转到管理员主界面
                    showAdminMainInterface();
                } else {
                    JOptionPane.showMessageDialog(this, "用户名或密码错误，请重试。", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "登录失败，请检查数据库连接。", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // 显示用户主界面
    private void showUserMainInterface(User user) {
        // 实现用户主界面逻辑
        JFrame userFrame = new JFrame("用户主界面 - " + user.getUsername());
        userFrame.setSize(400, 300);
        userFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        userFrame.setLocationRelativeTo(null);
        
        JLabel welcomeLabel = new JLabel("欢迎，" + user.getUsername());
        welcomeLabel.setHorizontalAlignment(JLabel.CENTER);
        userFrame.add(welcomeLabel, BorderLayout.CENTER);
        
        userFrame.setVisible(true);
    }

    // 显示管理员主界面
    private void showAdminMainInterface() {
        // 实现管理员主界面逻辑
        JFrame adminFrame = new JFrame("管理员主界面");
        adminFrame.setSize(400, 300);
        adminFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        adminFrame.setLocationRelativeTo(null);
        
        JLabel welcomeLabel = new JLabel("欢迎，管理员");
        welcomeLabel.setHorizontalAlignment(JLabel.CENTER);
        adminFrame.add(welcomeLabel, BorderLayout.CENTER);
        
        adminFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Home home = new Home();
                home.setVisible(true);
            }
        });
    }
}